package com.study.testSSMPlus.service.impl;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.TriggerBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.testSSMPlus.entity.Job;
import com.study.testSSMPlus.mapper.JobMapper;
import com.study.testSSMPlus.service.IJobService;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuyu
 * @since 2019-12-21
 */
@Service
public class JobServiceImpl extends ServiceImpl<JobMapper, Job> implements IJobService {

	@Autowired
	private Scheduler scheduler;
	
	@Autowired
	private JobMapper jobMapper;
	
	 public static final String TASK_PROPERTIES = "TASK_PROPERTIES";
	
	@SuppressWarnings("unchecked")
	@Override
	public void runJob(Integer jobId) {
		Job job = jobMapper.selectById(jobId);
		
		// 通过JobBuilder构建JobDetail实例，JobDetail规定只能是实现Job接口的实例
        // JobDetail 是具体Job实例
        JobDetail jobDetail = null;
		try {
			jobDetail = JobBuilder.newJob((Class<? extends org.quartz.Job>) Class.forName(
					job.getInvokeTarget())).withIdentity("job"+jobId, job.getJobGroup()).build();
			// 基于表达式构建触发器
			CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
			// CronTrigger表达式触发器 继承于Trigger
			// TriggerBuilder 用于构建触发器实例
			CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("job"+jobId, job.getJobGroup())
					.withSchedule(cronScheduleBuilder).build();
			scheduler.scheduleJob(jobDetail, cronTrigger);
			scheduler.start();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
	}

}
